<template>
  <div class="material-card" style="background-color: #ebecee;  min-height: 82vh;margin-left: 20px;margin-right:20px ;">

    <!-- 试卷预览区域 -->
    <div v-if="showPaperPreview" class="paper-preview-container p-5">
      <el-button type="primary" @click="closePaperPreview" class="mb-4">返回</el-button>

      <el-card shadow="hover" class="mb-4" style="margin-bottom: 20px;">
        <h2>{{ previewPaper.paperName }}</h2>
        <p>
          总分：<strong>{{ previewPaper.totalScore }}</strong> 分 ｜ 考试时长：
          <strong>{{ previewPaper.timeLimit }}</strong> 分钟
        </p>
      </el-card>

      <el-card v-for="(question, index) in previewPaper.questions" :key="question.questionId" class="mb-4"
        shadow="always" style="margin-bottom: 10px;">
        <template #header>
          <div class="flex justify-between items-center">
            <span><strong>
                <h2> 第{{ index + 1 }}题</h2>
              </strong></span>
            <el-button size="small" type="success" @click="saveQuestion(question)">保存</el-button>
          </div>
        </template>

        <!-- 富文本编辑器 -->
        <Editor v-model="question.content" :onCreated="(editor) => onEditorCreated(editor, question.questionId)"
          style="min-height: 200px; border: 1px solid #ccc; margin-bottom: 10px;" placeholder="请输入题目内容" />

        <!-- 解析显示切换按钮 -->
        <el-button size="mini" type="text" @click="toggleAnalysis(index)" style="margin-bottom: 8px;">
          {{ question.showAnalysis ? '隐藏解析' : '查看解析' }}
        </el-button>

        <!-- 解析内容 -->
        <div v-if="question.showAnalysis" class="analysis-content"
          style="border: 1px solid #eee; padding: 10px; background-color: #fafafa;" v-html="question.analysis"></div>

        <el-divider />
        <p>题型：<strong>{{ question.questionType }}</strong> ｜ 分数：<strong>{{ question.score }}</strong> 分</p>
      </el-card>
    </div>




    <div v-if="(activeTab === 'question' || activeTab === 'paper' || activeTab === 'custom') && !showPaperPreview">

      <div class="main-content">
        <!-- 添加标签栏 -->
        <el-tabs v-model="activeTab" type="card" @tab-click="handleTabChange">
          <el-tab-pane label="题目管理" name="question"></el-tab-pane>
          <el-tab-pane label="试卷管理" name="paper"></el-tab-pane>
          <el-tab-pane label="自定义组卷" name="custom"></el-tab-pane> <!-- ✅ 新增 -->

        </el-tabs>

        <div class="header">
          <h3>
            {{
              activeTab === 'question'
                ? '题目管理'
                : activeTab === 'paper'
                  ? '试卷管理'
                  : '自定义组卷'
            }}
          </h3>
        </div>

        <div class="material-card top-bar-card">
          <div  v-if="(activeTab === 'question' || activeTab === 'paper' )"  class="top-bar">
            <el-input v-model="searchKeyword" placeholder="请输入名称关键词" size="medium"
              style="width: 300px;margin-left: 10px;" clearable />
            <el-button class="custom-btn" @click="search">查询</el-button>
            <el-button v-if="activeTab === 'question'" class="custom-btn" type="success"
              @click="aiGenerateDialogVisible = true">
              新增题目
            </el-button>
            <el-button class="custom-btn" type="danger" @click="deleteSelected"
              :disabled="multipleSelection.length === 0">
              批量删除
            </el-button>
            <el-button v-if="activeTab === 'question'" class="custom-btn" type="success"
              @click="aiGenerateDialogVisible = true">
              智能出题
            </el-button>
            
<!-- 在智能出题对话框旁边添加PDF上传按钮 -->
<el-button type="success" @click="pdfUploadDialogVisible = true" style="margin-left: 10px;">
  <el-icon><Upload /></el-icon>
  PDF导题
</el-button>
            <!-- 
          <el-button v-if="activeTab !== 'question'" class="custom-btn" type="success" @click="opencreateDialog">
            根据现有题目自定义组卷
          </el-button> -->

          </div>

          <!-- 自定义组卷区域 -->

          <div v-if="activeTab === 'custom'" class="custom-paper-area" style="padding: 20px;">
            <!-- 选择课程 -->
            <el-form label-width="100px">
              <el-form-item label="选择课程">
                <el-select v-model="selectedCourseId" placeholder="请选择课程" @change="onCourseChange">
                  <el-option v-for="course in courseList" :key="course.courseId" :label="course.courseName"
                    :value="course.courseId" />
                </el-select>
              </el-form-item>

              <!-- 试卷名称 -->
<el-form-item label="试卷名称">
  <el-input
    v-model="paperName"
    placeholder="请输入试卷名称（留空则自动命名）"
    clearable
  />
</el-form-item>

<!-- 考试时间（分钟） -->
<el-form-item label="考试时间">
  <el-input-number
    v-model="timeLimit"
    :min="1"
    :step="5"
    placeholder="分钟"
    controls-position="right"
  />
</el-form-item>

<!-- 每题分数 -->
<el-form-item label="每题分数">
  <el-input-number
    v-model="questionScore"
    :min="1"
    placeholder="分"
    controls-position="right"
  />
</el-form-item>
              
              <!-- 多选知识点 -->
              <el-form-item label="选择知识点">
                <el-select v-model="selectedPointIds" multiple placeholder="请选择知识点" @change="onPointSelectionChange"
                  :disabled="!selectedCourseId">
                  <el-option v-for="point in knowledgePoints" :key="point.pointId" :label="point.pointName"
                    :value="point.pointId" />
                </el-select>
              </el-form-item>

              <!-- 知识点题型题量展示与设置 -->
              <el-table :data="pointTypeStats" border>
                <el-table-column prop="pointName" label="知识点" min-width="180px" />
                <el-table-column prop="questionType" label="题型" min-width="80px" />
                <el-table-column prop="count" label="题目数量" min-width="80px" />
                <el-table-column label="加入组卷的数量（随机选择）">
                  <template #default="scope">
                    <el-input-number :model-value="scope.row.selectCount"
                      @update:model-value="(val) => updateSelectedCount(scope.row, val)" :min="0" :max="scope.row.count"
                      size="small" />
                  </template>
                </el-table-column>
              </el-table>


              <!-- 操作按钮 -->
              <el-form-item>
                <el-button type="primary" @click="generatePaper">生成试卷</el-button>
                <el-button @click="resetCustomForm">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <div v-if="activeTab === 'question' || activeTab === 'paper'" class="material-card table-card">
          <!-- 题目表格 -->
          <el-table v-if="activeTab === 'question'" :data="questionTableData" style="width: 100%;"
            :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" />
            <el-table-column label="编号" width="60" prop="index" type="index" align="center" />
            <el-table-column prop="content" label="题目内容" show-overflow-tooltip />
            <el-table-column prop="questionType" label="所属题型" width="80" />
            <el-table-column prop="pointId" label="所属知识点" width="120" :formatter="formatPointName" />
            <el-table-column prop="difficulty" label="难度" width="60" />
            <el-table-column prop="createTime" label="创建时间" width="95">
              <template #default="scope">
                <div>
                  {{ formatDate(scope.row.createTime).date }}<br />
                  {{ formatDate(scope.row.createTime).time }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="上次修改时间" width="120">
              <template #default="scope">
                <div v-if="scope.row.updateTime">
                  {{ formatDate(scope.row.updateTime).date }}<br />
                  {{ formatDate(scope.row.updateTime).time }}
                </div>
                <div v-else>无修改记录</div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="题目状态" width="80" :formatter="formatStatus" />
            <el-table-column label="操作" width="220">
              <template #default="scope">
                <el-button size="small" class="custom-btn" @click="view(scope.row)">详情</el-button>
                <el-button size="small" class="custom-btn" @click="edit(scope.row)">修改</el-button>
                <el-button size="small" type="danger" class="custom-btn" @click="del(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 添加分页组件 -->
          <div v-if="activeTab === 'question'" class="pagination-container"
            style="margin-top: 20px; text-align: center;">
            <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
              :page-sizes="[5, 10, 20, 50]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange" @current-change="handlePageChange" :small="false" background />
          </div>

          <!-- 试卷表格 -->
          <el-table v-if="activeTab === 'paper'" :data="paperTableData" style="width: 100%;"
            :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="45" />
            <el-table-column prop="paperId" label="试卷ID" width="70" />
            <el-table-column prop="paperName" label="试卷名称" />
            <el-table-column label="所属课程" prop="courseId" width="120">
              <template #default="scope">
                {{ courseMap[scope.row.courseId] || '未知课程' }}
              </template>
            </el-table-column>
            <el-table-column prop="totalScore" label="总分" width="60" />
            <el-table-column prop="timeLimit" label="考试时长(分钟)" width="120" />
            <el-table-column prop="description" label="描述" show-overflow-tooltip />
            <el-table-column prop="createTime" label="创建时间" width="120">
              <template #default="scope">
                <div>
                  {{ formatDate(scope.row.createTime).date }}<br />
                  {{ formatDate(scope.row.createTime).time }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="60" :formatter="formatStatus" />
            <el-table-column label="操作" width="260">
              <template #default="scope">
                <el-button size="small" class="custom-btn" @click="preview(scope.row)">预览</el-button>
                <el-button size="small" class="custom-btn" @click="view(scope.row)">详情</el-button>
                <el-button size="small" class="custom-btn" @click="edit(scope.row)">修改</el-button>
                <el-button size="small" type="danger" class="custom-btn" @click="del(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </div>

        <!-- PDF上传对话框 -->
<el-dialog
  v-model="pdfUploadDialogVisible"
  title="PDF文件导入题目"
  width="600px"
  :before-close="handlePdfDialogClose"
  :close-on-click-modal="false"
>
  <el-form :model="pdfUploadForm" label-width="120px">
    <el-form-item label="选择课程" required>
      <el-select 
        v-model="pdfUploadForm.courseType" 
        placeholder="请选择课程" 
        style="width: 100%"
        @change="handlePdfCourseChange"
      >
        <el-option 
          v-for="course in courseList" 
          :key="course.courseId" 
          :label="course.courseName"
          :value="course.courseName" 
        />
      </el-select>
    </el-form-item>

    <el-form-item label="选择知识点" required>
      <el-select 
        v-model="pdfUploadForm.knowledgePoint" 
        placeholder="请选择知识点" 
        style="width: 100%"
        :disabled="!pdfUploadForm.courseType"
      >
        <el-option 
          v-for="point in pdfFilteredKnowledgePoints" 
          :key="point.pointId" 
          :label="point.pointName"
          :value="point.pointName" 
        />
      </el-select>
    </el-form-item>

    <el-form-item label="默认难度" required>
      <el-select v-model="pdfUploadForm.difficulty" placeholder="请选择难度" style="width: 100%">
        <el-option label="简单" value="1" />
        <el-option label="中等" value="2" />
        <el-option label="困难" value="3" />
      </el-select>
    </el-form-item>

    <el-form-item label="上传PDF" required>
      <el-upload
        ref="pdfUploadRef"
        class="upload-demo"
        drag
        :action="uploadAction"
        :headers="uploadHeaders"
        :data="uploadData"
        :before-upload="beforePdfUpload"
        :on-success="handlePdfUploadSuccess"
        :on-error="handlePdfUploadError"
        v-model:file-list="pdfFileList"
        :limit="1"
        :auto-upload="false"
        accept=".pdf"
        :disabled="pdfUploading"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将PDF文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传PDF文件，且不超过10MB
          </div>
        </template>
      </el-upload>
    </el-form-item>

    <!-- 预览提取的内容 -->
    <el-form-item label="提取内容" v-if="extractedText">
      <el-card class="extracted-content-card">
        <el-scrollbar height="200px">
          <div class="extracted-content" style="white-space: pre-wrap; font-size: 14px; line-height: 1.5;">
            {{ extractedText }}
          </div>
        </el-scrollbar>
        <div style="margin-top: 10px; color: #666; font-size: 12px;">
          提取字符数：{{ extractedText.length }}
        </div>
      </el-card>
    </el-form-item>

    <!-- 识别的题目列表 -->
    <el-form-item label="识别题目" v-if="recognizedQuestions.length > 0">
      <el-card>
        <template #header>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span>共识别到 {{ recognizedQuestions.length }} 道题目</span>
            <el-button size="small" type="primary" @click="debugUploadStatus" v-if="false">调试</el-button>
          </div>
        </template>
        
        <el-table 
          ref="recognizedQuestionsTable"
          :data="recognizedQuestions" 
          style="width: 100%" 
          max-height="300"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="content" label="题目内容" min-width="200" show-overflow-tooltip>
            <template #default="scope">
              <div style="max-width: 200px; overflow: hidden; text-overflow: ellipsis;">
                {{ scope.row.content }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="questionType" label="题型" width="80" />
          <el-table-column prop="answer" label="答案" width="100" show-overflow-tooltip />
          <el-table-column prop="difficulty" label="难度" width="60">
            <template #default="scope">
              {{ scope.row.difficulty == 1 ? '简单' : scope.row.difficulty == 2 ? '中等' : '困难' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button size="small" type="primary" @click="editRecognizedQuestion(scope.row)">
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-form-item>
  </el-form>

  <template #footer>
    <span class="dialog-footer">
      <el-button @click="pdfUploadDialogVisible = false" :disabled="pdfUploading">取消</el-button>
      <el-button 
        type="info" 
        @click="startPdfUpload" 
        :loading="pdfUploading" 
        v-if="pdfFileList.length > 0 && recognizedQuestions.length === 0"
      >
        {{ pdfUploading ? '正在解析...' : '开始解析' }}
      </el-button>
      <el-button 
        type="primary" 
        @click="saveRecognizedQuestions" 
        :loading="savingQuestions"
        v-if="recognizedQuestions.length > 0"
      >
        {{ savingQuestions ? '正在保存...' : '保存选中题目' }}
      </el-button>
    </span>
  </template>
</el-dialog>

<!-- 编辑识别题目的对话框 -->
<el-dialog
  v-model="editQuestionDialogVisible"
  title="编辑题目"
  width="700px"
  :modal-append-to-body="false"
>
  <el-form :model="editingQuestion" label-width="100px">
    <el-form-item label="题目内容" required>
      <el-input 
        v-model="editingQuestion.content" 
        type="textarea" 
        :rows="4"
        placeholder="请输入题目内容"
      />
    </el-form-item>
    <el-form-item label="题目类型" required>
      <el-select v-model="editingQuestion.questionType" style="width: 100%">
        <el-option label="选择题" value="选择题" />
        <el-option label="判断题" value="判断题" />
        <el-option label="填空题" value="填空题" />
        <el-option label="简答题" value="简答题" />
      </el-select>
    </el-form-item>
    <el-form-item label="答案" required>
      <el-input v-model="editingQuestion.answer" placeholder="请输入答案" />
    </el-form-item>
    <el-form-item label="解析">
      <el-input 
        v-model="editingQuestion.analysis" 
        type="textarea" 
        :rows="3"
        placeholder="请输入题目解析"
      />
    </el-form-item>
    <el-form-item label="难度" required>
      <el-select v-model="editingQuestion.difficulty" style="width: 100%">
        <el-option label="简单" value="1" />
        <el-option label="中等" value="2" />
        <el-option label="困难" value="3" />
      </el-select>
    </el-form-item>
  </el-form>
  
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="editQuestionDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="savePdfEditedQuestion">保存</el-button>
    </span>
  </template>
</el-dialog>



        <!-- 题目添加/修改弹窗 -->
        <el-dialog v-model="dialogVisible" :title="isEditing ? '修改题目' : '新增题目'" width="600px"
          v-if="activeTab === 'question'">
          <el-form :model="currentQuestion" label-width="100px">
            <el-form-item label="题号" v-if="isEditing">
              <el-input v-model="currentQuestion.questionId" disabled />
            </el-form-item>
            <el-form-item label="题目内容">
              <el-input v-model="currentQuestion.content" type="textarea" rows="3" />
            </el-form-item>
            <el-form-item label="题型">
              <el-input v-model="currentQuestion.questionType" />
            </el-form-item>
            <el-form-item label="知识点编号">
              <el-input v-model="currentQuestion.pointId" />
            </el-form-item>
            <el-form-item label="难度">
              <el-select v-model="currentQuestion.difficulty" placeholder="请选择">
                <el-option label="简单" value="1" />
                <el-option label="中等" value="2" />
                <el-option label="较难" value="3" />
              </el-select>
            </el-form-item>
            <el-form-item label="正确答案">
              <el-input v-model="currentQuestion.answer" />
            </el-form-item>
            <el-form-item label="解析">
              <el-input v-model="currentQuestion.analysis" type="textarea" rows="2" />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="currentQuestion.status">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-form>

          <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="save">保存</el-button>
          </template>
        </el-dialog>

        <!-- 试卷添加/修改弹窗 -->
        <el-dialog v-model="dialogVisible" :title="isEditing ? '修改试卷' : '新增试卷'" width="600px" v-else>
          <el-form :model="currentPaper" label-width="120px">
            <el-form-item label="试卷ID" v-if="isEditing">
              <el-input v-model="currentPaper.paperId" disabled />
            </el-form-item>
            <el-form-item label="试卷名称">
              <el-input v-model="currentPaper.paperName" />
            </el-form-item>
            <el-form-item label="所属课程ID">
              <el-input v-model="currentPaper.courseId" />
            </el-form-item>
            <el-form-item label="总分">
              <el-input v-model="currentPaper.totalScore" type="number" />
            </el-form-item>
            <el-form-item label="考试时长(分钟)">
              <el-input v-model="currentPaper.timeLimit" type="number" />
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="currentPaper.description" type="textarea" rows="2" />
            </el-form-item>
            <el-form-item label="包含题目">
              <el-select v-model="currentPaper.questionIds" multiple placeholder="请选择题目">
                <el-option v-for="question in questionTableData" :key="question.questionId" :label="question.content"
                  :value="question.questionId" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="currentPaper.status">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-form>

          <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="save">保存</el-button>
          </template>
        </el-dialog>




        <!-- 题目/试卷详情弹窗 -->
        <el-dialog v-model="detailDialogVisible" :title="activeTab === 'question' ? '题目详情' : '试卷详情'" width="600px"
          :show-close="true">
          <div v-if="activeTab === 'question'">
            <p><strong>题号：</strong>{{ currentQuestion.questionId }}</p>
            <p><strong>题目内容：</strong>{{ currentQuestion.content }}</p>
            <p><strong>所属知识点编号：</strong>{{ currentQuestion.pointId }}</p>
            <p><strong>所属知识点：</strong>{{ pointMap[currentQuestion.pointId] || '未知知识点' }}</p>
            <p><strong>题型：</strong>{{ currentQuestion.questionType }}</p>
            <p><strong>难度：</strong>{{ currentQuestion.difficulty }}</p>
            <p><strong>举报次数：</strong>{{ currentQuestion.reportedCount }}</p>
            <p><strong>创建时间：</strong>{{ currentQuestion.createTime }}</p>
            <p><strong>分析：</strong>{{ currentQuestion.analysis }}</p>
            <p><strong>答案：</strong>{{ currentQuestion.answer }}</p>
            <p><strong>上次时间修改：</strong>{{ currentQuestion.updateTime || '没有修改记录' }}</p>
            <p><strong>状态：</strong>{{ currentQuestion.status == 1 ? '启用' : '禁用' }}</p>
          </div>
          <div v-else>
            <p><strong>试卷ID：</strong>{{ currentPaper.paperId }}</p>
            <p><strong>试卷名称：</strong>{{ currentPaper.paperName }}</p>
            <p><strong>所属课程id：</strong>{{ currentPaper.courseId }}</p>
            <p><strong>所属课程：</strong>{{ courseMap[currentPaper.courseId] || '未知课程' }}</p>
            <p><strong>总分：</strong>{{ currentPaper.totalScore }}</p>
            <p><strong>考试时长：</strong>{{ currentPaper.timeLimit }}分钟</p>
            <p><strong>包含题目数：</strong>{{ currentPaper.questionIds ? currentPaper.questionIds.length : 0 }}</p>
            <p><strong>描述：</strong>{{ currentPaper.description }}</p>
            <p><strong>创建时间：</strong>{{ currentPaper.createTime }}</p>
            <p><strong>状态：</strong>{{ currentPaper.status == 1 ? '启用' : '禁用' }}</p>
            <!--  <el-button @click="openPreview(currentPaper.paperId)" class="custom-btn">预览试卷</el-button>-->
            <el-button @click="analyzePaper(currentPaper.paperId)" class="custom-btn">用户答题分析</el-button>




          </div>

          <template #footer>
            <el-button @click="detailDialogVisible = false">关闭</el-button>
          </template>
        </el-dialog>

        <!-- 试卷预览弹窗 -->
        <el-dialog v-model="previewDialogVisible" title="试卷预览" width="700px" :close-on-click-modal="false">
          <div v-if="previewQuestions.length > 0">
            <div v-for="(q, index) in previewQuestions" :key="q.id" class="question-preview-item">
              <p><strong>题目 {{ index + 1 }}（分值：{{ q.score }}）：</strong></p>
              <p style="margin-left: 20px;">{{ q.content }}</p>
              <p style="margin-left: 20px;"><strong>题型：</strong>{{ q.questionType }}，
                <strong>难度：</strong>{{ q.difficulty }}，
                <strong>知识点：</strong>{{ pointMap[q.pointId] || '未知' }}
              </p>
              <p style="margin-left: 20px;"><strong>答案：</strong>{{ q.answer }}</p>
              <p style="margin-left: 20px;"><strong>解析：</strong>{{ q.analysis }}</p>
              <el-divider />
            </div>
          </div>
          <div v-else>
            <p>该试卷暂无题目。</p>
          </div>

          <template #footer>
            <el-button @click="previewDialogVisible = false">关闭</el-button>
          </template>
        </el-dialog>


      </div>
    </div>
  </div>

  <el-dialog v-model="dialoganalysisVisible" title="试卷分析结果" width="600px" :close-on-click-modal="false">
    <div v-if="analysis">
      <p>
        平均试卷得分：
        <span v-if="analysis && analysis.avgPaperScore !== undefined">
          {{ analysis.avgPaperScore.toFixed(2) }}
        </span>
        <span v-else>-</span>
      </p>
      <p>
        平均用时：
        <span v-if="analysis && analysis.avgPaperTimeSpent !== undefined">
          {{ analysis.avgPaperTimeSpent }} 秒
        </span>
        <span v-else>-</span>
      </p>
    </div>
    <template #footer>
      <el-button @click="dialoganalysisVisible = false">关闭</el-button>
    </template>
  </el-dialog>

  <!-- 智能出题对话框 -->
  <el-dialog v-model="aiGenerateDialogVisible" title="智能出题" width="500px" :close-on-click-modal="false">
    <el-form :model="aiGenerateForm" label-width="100px">
      <el-form-item label="课程类型">
        <el-select v-model="aiGenerateForm.courseType" placeholder="请选择课程类型" style="width: 100%"
          @change="handleCourseChange" clearable>
          <el-option v-for="course in courseList" :key="course.courseId" :label="course.courseName"
            :value="course.courseName">
            {{ course.courseName }}
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="题型">
        <el-select v-model="aiGenerateForm.questionType" placeholder="请选择题型" style="width: 100%">
          <el-option label="选择题" value="选择题" />
          <el-option label="应用题" value="应用题" />
          <el-option label="算法题" value="算法题" />
          <el-option label="综合题" value="综合题" />
        </el-select>
      </el-form-item>

      <el-form-item label="知识点">
        <el-select v-model="aiGenerateForm.knowledgePoint" placeholder="请选择知识点" style="width: 100%"
          :disabled="!aiGenerateForm.courseType">
          <el-option v-for="point in filteredKnowledgePoints" :key="point.pointId" :label="point.pointName"
            :value="point.pointName" />
        </el-select>
      </el-form-item>

      <el-form-item label="难度">
        <el-select v-model="aiGenerateForm.difficulty" placeholder="请选择难度" style="width: 100%">
          <el-option label="简单" value="1" />
          <el-option label="中等" value="2" />
          <el-option label="困难" value="3" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="aiGenerateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAIGenerate" :loading="generating">
          生成题目
        </el-button>
      </span>
    </template>
  </el-dialog>


</template>




<script setup>
import { ref, onMounted, reactive, watch, computed, onBeforeUnmount, shallowRef } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useRoute } from 'vue-router'

const paperName      = ref('')   // 试卷名称
const timeLimit      = ref(60)   // 考试时间（分钟）
const questionScore  = ref(2)    // 每题分数
const route = useRoute()
const pdfUploadRef = ref(null)

const editorInstance = ref(null) // ← 加上这一行

// 1. 添加分页相关的响应式数据
const pagination = ref({
  currentPage: 1,    // 当前页码
  pageSize: 10,      // 每页显示数量
  total: 0,          // 总记录数
  totalPages: 0      // 总页数
})



// 路由变化时重新加载数据
watch(() => route.fullPath, () => {
  questionTableData.value = [];
  paperTableData.value = [];
  loadQuestionData();
  loadPaperData();
});

// 组件挂载时加载数据
onMounted(() => {
  loadQuestionData();
  loadPaperData();
});



//富文本编辑器引入
const editDialogVisible = ref(false)
const currentEditingQuestion = ref(null)
const editor = ref(null)
const editorContainer = ref(null)

onBeforeUnmount(() => {
  // 清理组件状态
  questionTableData.value = []
  paperTableData.value = []
  if (editorInstance.value) {
    editorInstance.value.destroy()
    editorInstance.value = null
  }
})


watch(editDialogVisible, (visible) => {
  if (visible) {
    if (editorInstance.value && !editorInitialized.value) {
      // 弹窗打开且编辑器已创建，初始化内容
      editorInstance.value.setHtml(currentEditingQuestion.value?.content || '')
      editorInitialized.value = true
    }
  } else {
    editorInitialized.value = false
  }
})

// 编辑器创建回调
function onEditorCreated(editor) {
  editorInstance.value = editor
  editor.config.onChange = (editor) => {
    // 实时同步编辑器内容到 currentEditingQuestion
    currentEditingQuestion.value.content = editor.getHtml()
  }
}

// 弹窗保存内容时，先更新数据，再请求后台保存
async function saveEditedQuestion() {
  if (currentEditingQuestion.value && editorInstance.value) {
    currentEditingQuestion.value.content = editorInstance.value.getHtml()
    // 调用接口保存
    await saveQuestion(currentEditingQuestion.value)
  }
  editDialogVisible.value = false
}

// 关闭弹窗销毁编辑器实例
function handleClose(done) {

  done()
}




// 保存题目内容到后台接口
async function saveQuestion(question) {
  try {
    const res = await axios.put('http://localhost:8080/question/update', question)
    if (res.data === '修改成功') {
      ElMessage.success('保存成功！')
    } else {
      ElMessage.error('保存失败！')
    }
  } catch (error) {
    ElMessage.error('保存异常！')
    console.error(error)
  }
}

// ========== 组卷相关 ==========
//试卷预览
function preview(paper) {
  const paperId = paper.paperId || paper.id; // 根据你的表格字段实际名称
  previewPaperById(paperId);
}
//关闭预览
function closePaperPreview() {
  showPaperPreview.value = false;
  this.previewPaper = {}; // 可选：清空
}

function editQuestionInPreview(question) {
  currentEditingQuestion.value = question
  editDialogVisible.value = true
}

//重置方法
const resetCustomForm = () => {
  selectedCourseId.value = null
  selectedPointIds.value = []
  pointTypeStats.value = []
}

const showPaperPreview = ref(false); // 控制显示
const previewPaper = ref({
  paperName: '',
  totalScore: 0,
  timeLimit: 0,
  questions: []
});


// 课程和知识点
const selectedCourseId = ref(null)
const knowledgePoints = ref([])
const selectedPointIds = ref([])
const courseList = ref([])

// 知识点 → 题型统计:{ pointId: { 单选: 10, 判断: 5 } }
const questionStats = ref({})

// 用户设定的数量:{ pointId: { 单选: 3, 判断: 2 } }
const selectedCounts = ref({})

// 获取所有课程
const fetchCourses = async () => {
  console.log('=== 开始获取课程列表 ===')
  try {
    console.log('正在发送请求到: http://localhost:8080/Courses/all')
    const res = await axios.get('http://localhost:8080/Courses/all')
    console.log('请求成功,响应状态:', res.status)
    console.log('响应数据:', res.data)

    if (res.data) {
      console.log('设置课程列表前的数据:', courseList.value)
      courseList.value = res.data
      console.log('设置课程列表后的数据:', courseList.value)
    } else {
      console.error('课程数据为空')
      ElMessage.error('获取课程列表失败:数据为空')
    }
  } catch (error) {
    console.error('获取课程列表失败,错误详情:', error)
    console.error('错误信息:', error.message)
    console.error('错误响应:', error.response)
    ElMessage.error('获取课程列表失败:' + (error.message || '未知错误'))
  }
  console.log('=== 获取课程列表结束 ===')
}

// 获取某课程的知识点 - 保持原有的函数名和参数类型
const onCourseChange = async (courseId) => {
  console.log('=== 课程选择变化 ===')
  console.log('选择的课程ID:', courseId)

  try {
    selectedCourseId.value = courseId
    console.log('准备获取知识点,课程ID:', courseId)

    // 获取该课程下的知识点
    const res = await axios.get(`http://localhost:8080/KnowledgePoint/course?courseId=${courseId}`)
    console.log('知识点接口返回数据:', res.data)

    if (res.data) {
      console.log('设置知识点列表前的数据:', knowledgePoints.value)
      knowledgePoints.value = res.data
      console.log('设置知识点列表后的数据:', knowledgePoints.value)

      // 重置相关状态
      selectedPointIds.value = []
      questionStats.value = {}
      selectedCounts.value = {}
    } else {
      console.error('知识点数据为空')
      ElMessage.error('获取课程知识点失败:数据为空')
    }
  } catch (error) {
    console.error('获取课程知识点失败,错误详情:', error)
    console.error('错误信息:', error.message)
    console.error('错误响应:', error.response)
    ElMessage.error('获取课程知识点失败:' + (error.message || '未知错误'))
  }
  console.log('=== 课程选择处理完成 ===')
}

// 获取题型统计
const onPointSelectionChange = async () => {
  console.log('=== 知识点选择变化 ===')
  console.log('选中的知识点IDs:', selectedPointIds.value)

  questionStats.value = {}
  selectedCounts.value = {}

  for (const pid of selectedPointIds.value) {
    try {
      console.log(`正在获取知识点 ${pid} 的题目统计`)
      const res = await axios.get(`http://localhost:8080/question/getbypid?pointId=${pid}`)
      console.log(`知识点 ${pid} 的题目数据:`, res.data)

      const stats = {}
      for (const q of res.data) {
        stats[q.questionType] = (stats[q.questionType] || 0) + 1
      }
      questionStats.value[pid] = stats
      console.log(`知识点 ${pid} 的题型统计:`, stats)

      // 初始化选中数量为 0
      const initCount = {}
      Object.keys(stats).forEach(t => (initCount[t] = 0))
      selectedCounts.value[pid] = initCount
      console.log(`知识点 ${pid} 的初始选择数量:`, initCount)
    } catch (e) {
      console.error(`加载 pointId=${pid} 的题目失败:`, e)
      ElMessage.error(`加载 pointId=${pid} 的题目失败`)
    }
  }
  console.log('=== 知识点选择处理完成 ===')
  console.log('最终题型统计:', questionStats.value)
  console.log('最终选择数量:', selectedCounts.value)
}

// 页面加载时获取课程列表
onMounted(() => {
  fetchCourses()
})



// 1. 展示用的表格数组
const pointTypeStats = computed(() => {
  const result = []
  for (const pid in questionStats.value) {
    const point = knowledgePoints.value.find(p => p.pointId === Number(pid))
    for (const type in questionStats.value[pid]) {
      result.push({
        pointId: pid,
        pointName: point ? point.pointName : '',
        questionType: type,
        count: questionStats.value[pid][type],
        selectCount: selectedCounts.value[pid]?.[type] ?? 0
      })
    }
  }
  return result
})

// 2. 同步用户修改的 selectCount 到 selectedCounts
const updateSelectedCount = (row, val) => {
  const { pointId, questionType } = row
  if (!selectedCounts.value[pointId]) selectedCounts.value[pointId] = {}
  selectedCounts.value[pointId][questionType] = val
}


// 组卷逻辑：按知识点 + 题型 + 数量 → 抽题
const generatePaper = async () => {
  
  const ruleList = []
  for (const pid in selectedCounts.value) {
    for (const type in selectedCounts.value[pid]) {
      const count = selectedCounts.value[pid][type]
      if (count > 0) {
        ruleList.push({ pointId: pid, questionType: type, count })
      }
    }
  }

  const allSelectedQuestions = []

  for (const rule of ruleList) {
    const { pointId, questionType, count } = rule
    try {
      const res = await axios.get(`http://localhost:8080/question/getbypid?pointId=${pointId}`)
      const filtered = res.data.filter(q => q.questionType === questionType)

      if (filtered.length < count) {
        ElMessage.error(`知识点 ${pointId} 的 ${questionType} 题目不足`)
        return
      }

      // 随机抽取 count 个
      const shuffled = filtered.sort(() => 0.5 - Math.random())
      const selected = shuffled.slice(0, count)
      allSelectedQuestions.push(...selected)
    } catch (e) {
      ElMessage.error(`抽题失败：pointId=${pointId}`)
      return
    }
  }

  // 创建试卷对象
const paper = {
  paperName: paperName.value?.trim() || `自动组卷-${Date.now()}`,
  courseId: selectedCourseId.value,
  totalScore: allSelectedQuestions.length * questionScore.value, // ← 每题分数
  timeLimit: timeLimit.value,                                   // ← 考试时长
  description: '自定义生成的试卷',
  status: 1
}

  const res = await axios.post('http://localhost:8080/exam-papers/add', paper)

  const paperData = res.data

  // 判断是否返回了有效的 paperId
  if (!paperData || !paperData.paperId) {
    ElMessage.error('组卷失败，试卷创建失败（无返回 paperId）')
    return
  }

  const paperId = paperData.paperId



// paper_question 列表
const paperQuestions = allSelectedQuestions.map((q, index) => ({
  paperId,
  questionId: q.questionId,
  questionOrder: index + 1,
  score: questionScore.value       // ← 每题分数
}))

  try {
  const insertRes = await axios.post('http://localhost:8080/paperQuestion/batch-insert', paperQuestions)

  if (insertRes.status === 200 && insertRes.data === '插入成功') {
  ElMessage.success('组卷成功')
  createDialogVisible.value = false
  loadPaperData()
} else {
  ElMessage.error('组卷失败')
}
} catch (e) {
 
}
}


const handleSelectionChange = (val) => {
  multipleSelection.value = val // 如果 multipleSelection 是 ref([])
}


// 添加试卷分析内容

const props = defineProps({
  currentPaper: Object,
  courseMap: Object
})

const dialoganalysisVisible = ref(false);

const analysis = ref(null)
//试卷分析实现
function analyzePaper(paperId) {
  console.log('点击分析，paperId:', paperId);
  axios.get(`http://localhost:8080/exam-analysis/summary/${paperId}`)
    .then(res => {
      analysis.value = res.data
      dialoganalysisVisible.value = true
    })
    .catch(err => {
      ElMessage.error("获取试卷分析失败：" + err)
    })
}

const activeTab = ref('question') // 当前激活的标签页
const questionTableData = ref([]) // 题目数据
const paperTableData = ref([]) // 试卷数据
const searchKeyword = ref('')
const multipleSelection = ref([])

const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const isEditing = ref(false)

// 知识点表全查询，在页面加载时调用一次 API 拿到所有知识点，然后构建一个 pointMap
const pointMap = ref({})

const fetchKnowledgePoints = async () => {
  const res = await axios.get('http://localhost:8080/KnowledgePoint/all')
  const map = {}
  res.data.forEach(item => {
    map[item.pointId] = item.pointName
  })
  pointMap.value = map
}
onMounted(() => {
  fetchKnowledgePoints()
})

//显示知识点名称
const formatPointName = (row) => {
  return pointMap.value[row.pointId] || '未知'
}

// 课程表全查询，在页面加载时调用一次 API 拿到所有知识点，然后构建一个 courseMap
const courseMap = ref({})

const fetchCourseMap = async () => {
  const res = await axios.get('http://localhost:8080/Courses/all')
  const map = {}
  res.data.forEach(item => {
    map[item.courseId] = item.courseName
  })
  courseMap.value = map
}
onMounted(() => {
  fetchCourseMap()
})



// 题目相关数据
const currentQuestion = ref({
  questionId: null,
  content: '',
  questionType: '',
  pointId: '',
  difficulty: null,
  answer: '',
  analysis: '',
  reportedCount: 0,
  createTime: '',
  updateTime: '',
  status: '',
})

// 试卷相关数据
const currentPaper = ref({
  paperId: null,
  paperName: '',
  courseId: '',
  totalScore: 0,
  timeLimit: 0,
  description: '',
  questionIds: [],
  createTime: '',
  status: 1,
})


const formatStatus = (row, column, cellValue) => {
  return cellValue === 1 ? '启用' : '禁用';
};


const difficultyMap = {
  1: '简单',
  2: '中等',
  3: '较难',
}

//时间格式修改
function formatDate(dateTimeStr) {
  const date = new Date(dateTimeStr);
  const yyyyMMdd = date.toLocaleDateString();      // 2025/6/3 或 2025-06-03（根据浏览器设置）
  const hhmmss = date.toTimeString().slice(0, 8);   // 09:51:49
  return {
    date: yyyyMMdd,
    time: hhmmss
  };
}
// 3. 替换原来的loadQuestionData函数
const loadQuestionData = (page = 1, size = 10) => {
  axios.get(`http://localhost:8080/question/allpage?page=${page}&size=${size}`)
    .then(res => {
      const pageInfo = res.data

      // 处理分页数据
      questionTableData.value = pageInfo.list.map(item => ({
        ...item,
        difficulty: difficultyMap[item.difficulty] || '未知'
      }))

      // 更新分页信息
      pagination.value = {
        currentPage: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
        total: pageInfo.total,
        totalPages: pageInfo.pages
      }
    })
    .catch(err => {
      console.error('加载题目失败:', err)
      ElMessage.error('加载题目失败')
    })
}

// 4. 添加分页处理函数
const handlePageChange = (page) => {
  pagination.value.currentPage = page
  loadQuestionData(page, pagination.value.pageSize)
}

const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1  // 改变每页大小时回到第一页
  loadQuestionData(1, size)
}



// 加载试卷数据
const loadPaperData = () => {
  axios.get('http://localhost:8080/exam-papers/list/all')
    .then(res => {
      paperTableData.value = res.data.map(paper => ({
        ...paper,
        createTime: paper.createTime
      }))
    })
    .catch(err => {
      ElMessage.error('加载试卷失败')
      console.error(err)
    })
}


// 修改搜索函数中的试卷查询部分
const search = () => {
  if (!searchKeyword.value) {
    activeTab.value === 'question' ? loadQuestionData() : loadPaperData()
    return
  }

  const keyword = searchKeyword.value.trim().toLowerCase()
  if (!keyword) {
    // 如果搜索关键词为空，加载第一页数据
    loadQuestionData(1, pagination.value.pageSize)
    return
  }
  if (activeTab.value === 'question') {
    // 搜索时先获取所有数据再过滤（或者后端提供搜索接口会更好）
    axios.get('http://localhost:8080/question/all')
      .then(res => {
        const filteredData = res.data
          .filter(item => item.content.toLowerCase().includes(keyword))
          .map(item => ({
            ...item,
            difficulty: difficultyMap[item.difficulty] || '未知'
          }))

        questionTableData.value = filteredData

        // 更新分页信息（搜索结果）
        pagination.value = {
          currentPage: 1,
          pageSize: filteredData.length,
          total: filteredData.length,
          totalPages: 1
        }
      })
      .catch(() => {
        ElMessage.error('查询题目失败')
      })
  } else {
    // 修改试卷搜索逻辑
    axios.get('http://localhost:8080/exam-papers/list/all')
      .then(res => {
        paperTableData.value = res.data
          .filter(paper => paper.paperName.toLowerCase().includes(keyword))
          .map(paper => ({
            ...paper,
            createTime: paper.createTime
          }))
      })
      .catch(() => {
        ElMessage.error('查询试卷失败')
      })
  }
}

// 6. 在组件挂载时加载第一页数据
onMounted(() => {
  loadQuestionData(1, pagination.value.pageSize)
})


const openAddDialog = () => {
  if (activeTab.value === 'question') {
    currentQuestion.value = {
      questionId: null,
      content: '',
      questionType: '',
      difficulty: null,
      answer: '',
      analysis: '',
      reportedCount: 0,
      createTime: '',
      updateTime: '',
      pointId: '',
      status: '',
    }
  } else {
    currentPaper.value = {
      paperId: null,
      title: '',
      totalScore: 100,
      timeLimit: 120,
      questionIds: [],
      createTime: '',
      updateTime: '',
      status: 1,
    }
  }
  isEditing.value = false
  dialogVisible.value = true
}

const edit = (row) => {
  if (activeTab.value === 'question') {
    currentQuestion.value = {
      ...row,
      difficulty: Object.entries(difficultyMap).find(([k, v]) => v === row.difficulty)?.[0] || null
    }
  } else {
    currentPaper.value = { ...row }
  }
  isEditing.value = true
  dialogVisible.value = true
}

const view = (row) => {
  if (activeTab.value === 'question') {
    currentQuestion.value = { ...row }
  } else {
    currentPaper.value = { ...row }
  }
  detailDialogVisible.value = true
}

const save = () => {
  if (activeTab.value === 'question') {
    if (!currentQuestion.value.content || !currentQuestion.value.questionType || !currentQuestion.value.difficulty) {
      ElMessage.warning('请填写完整题目信息')
      return
    }

    const payload = {
      ...currentQuestion.value,
      difficulty: parseInt(currentQuestion.value.difficulty),
    }

    if (isEditing.value) {
      axios.put('http://localhost:8080/question/update', payload)
        .then(() => {
          ElMessage.success('修改题目成功')
          dialogVisible.value = false
          loadQuestionData()
        })
        .catch(() => {
          ElMessage.error('修改题目失败')
        })
    } else {
      axios.post('http://localhost:8080/question/add', payload)
        .then(() => {
          ElMessage.success('添加题目成功')
          dialogVisible.value = false
          loadQuestionData()
        })
        .catch(() => {
          ElMessage.error('添加题目失败')
        })
    }
  } else {
    if (!currentPaper.value.paperName || !currentPaper.value.totalScore || !currentPaper.value.timeLimit) {
      ElMessage.warning('请填写完整试卷信息')
      return
    }

    const payload = {
      ...currentPaper.value,
      totalScore: parseInt(currentPaper.value.totalScore),
      timeLimit: parseInt(currentPaper.value.timeLimit),
      paperName: currentPaper.value.paperName,
      courseId: currentPaper.value.courseId,  // 一定要加上这个
      paperId: currentPaper.value.paperId,  // 修改时必须指定主键id
      paperName: currentPaper.value.paperName,
      courseId: currentPaper.value.courseId,
      totalScore: parseInt(currentPaper.value.totalScore),
      timeLimit: parseInt(currentPaper.value.timeLimit),
      description: currentPaper.value.description,
      status: currentPaper.value.status
    }

    const request = isEditing.value
      ? axios.put(`http://localhost:8080/exam-papers/update/${currentPaper.value.paperId}`, payload)
      : axios.post('http://localhost:8080/exam-papers/add', payload)

    request.then(() => {
      ElMessage.success(isEditing.value ? '修改试卷成功' : '添加试卷成功')
      dialogVisible.value = false
      loadPaperData()
    })
      .catch((err) => {
        ElMessage.error(isEditing.value ? '修改试卷失败' : '添加试卷失败')
        console.error(err)
      })
  }
}

const del = (row) => {
  const type = activeTab.value === 'question' ? '题目' : '试卷'
  const idField = activeTab.value === 'question' ? 'questionId' : 'paperId'
  const id = row[idField]

  if (!id) {
    ElMessage.error(`${type}ID 无效，无法删除`)
    return
  }

  ElMessageBox.confirm(`确定删除${type}ID为 ${id} 的记录吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    const url = activeTab.value === 'question'
      ? `http://localhost:8080/question/delete/${id}`
      : `http://localhost:8080/exam-papers/del/${id}`

    axios.delete(url)
      .then(() => {
        ElMessage.success('删除成功')
        activeTab.value === 'question' ? loadQuestionData() : loadPaperData()
      })
      .catch((err) => {
        ElMessage.error('删除失败')
        console.error(err)
      })
  }).catch(() => { })
}

const deleteSelected = () => {
  if (multipleSelection.value.length === 0) return

  const type = activeTab.value === 'question' ? '题目' : '试卷'
  const idField = activeTab.value === 'question' ? 'questionId' : 'paperId'
  const ids = multipleSelection.value.map(item => item[idField])

  ElMessageBox.confirm(`确定批量删除${type}ID为 ${ids.join(', ')} 的记录吗？`, '警告', {
    type: 'warning'
  }).then(() => {
    Promise.all(ids.map(id => {
      const url = activeTab.value === 'question'
        ? `http://localhost:8080/question/delete/${id}`
        : `http://localhost:8080/exam-papers/del/${id}`
      return axios.delete(url)
    })).then(() => {
      ElMessage.success('批量删除成功')
      multipleSelection.value = []
      activeTab.value === 'question' ? loadQuestionData() : loadPaperData()
    }).catch(() => {
      ElMessage.error('批量删除失败')
    })
  }).catch(() => { })
}

const handleTabChange = (tab) => {
  activeTab.value = tab.paneName;
  search(); // 可根据 tab 加载对应数据
};


// 页面加载时调用
onMounted(() => {
  loadQuestionData()
  loadPaperData()
  search();
})



// 显示预览
const previewPaperById = async (paperId) => {
  try {
    // 1. 获取试卷题目关联信息
    const resp = await axios.get('http://localhost:8080/paperQuestion/byPaper', {
      params: { paper_id: paperId }
    })
    const paperQuestions = resp.data || []

    // 2. 遍历调用 question/get 接口获取每道题内容
    const questions = []
    let totalScore = 0

    for (const pq of paperQuestions) {
      const qResp = await axios.get('http://localhost:8080/question/get', {
        params: { questionId: pq.questionId }
      })
      const question = qResp.data
      question.score = pq.score
      question.questionOrder = pq.questionOrder
      question.showAnalysis = false  // ⬅️ 添加这个字段
      questions.push(question)
      totalScore += pq.score
    }

    // 3. 排序题目
    questions.sort((a, b) => a.questionOrder - b.questionOrder)

    // 4. 设置预览数据
    previewPaper.value = {
      paperName: `试卷 ${paperId}`,
      totalScore: totalScore,
      timeLimit: 60, // 写死也行，后续可从数据库获取
      questions
    }

    showPaperPreview.value = true
  } catch (error) {
    console.error('预览试卷出错:', error)
  }
}

const toggleAnalysis = (index) => {
  previewPaper.value.questions[index].showAnalysis =
    !previewPaper.value.questions[index].showAnalysis
}


// 修改智能出题处理函数
const handleAIGenerate = async () => {
  console.log('=== 开始生成题目 ===')
  // 表单验证
  if (!aiGenerateForm.value.courseType ||
    !aiGenerateForm.value.questionType ||
    !aiGenerateForm.value.knowledgePoint ||
    !aiGenerateForm.value.difficulty) {
    ElMessage.warning('请填写完整的题目信息')
    return
  }

  generating.value = true
  try {
    console.log('当前表单数据:', aiGenerateForm.value)

    // 找到选中课程的ID
    const selectedCourse = courseList.value.find(c => c.courseName === aiGenerateForm.value.courseType)
    if (!selectedCourse) {
      throw new Error('未找到对应的课程信息')
    }
    console.log('找到的课程信息:', selectedCourse)

    // 找到选中知识点的ID
    const selectedPoint = filteredKnowledgePoints.value.find(p => p.pointName === aiGenerateForm.value.knowledgePoint)
    if (!selectedPoint) {
      throw new Error('未找到对应的知识点信息')
    }
    console.log('找到的知识点信息:', selectedPoint)

    // 构建查询字符串
    const query = `请生成一道${aiGenerateForm.value.courseType}的${aiGenerateForm.value.questionType}，知识点是${aiGenerateForm.value.knowledgePoint}，难度为${aiGenerateForm.value.difficulty}`
    console.log('生成的查询字符串:', query)

    // 修改请求格式
    const response = await axios({
      method: 'post',
      url: 'http://localhost:8080/api/question/generate',
      headers: {
        'Content-Type': 'application/json'
      },
      data: {
        query: query,
        courseId: selectedCourse.courseId,
        pointId: selectedPoint.pointId
      }
    })

    console.log('AI生成响应:', response.data)

    if (response.data) {
      // 解析AI返回的JSON数据
      let aiResponse
      try {
        // 尝试从响应中提取JSON字符串
        const jsonStr = response.data.match(/```json\n([\s\S]*?)\n```/)?.[1]
        if (jsonStr) {
          // 清理JSON字符串中的特殊字符
          const cleanJsonStr = jsonStr
            .replace(/[\u0000-\u001F\u007F-\u009F]/g, '') // 移除控制字符
            .replace(/\n/g, ' ') // 将换行符替换为空格
            .replace(/\r/g, '') // 移除回车符
            .replace(/\t/g, ' ') // 将制表符替换为空格
            .replace(/\s+/g, ' ') // 将多个空格替换为单个空格
            .trim() // 移除首尾空格

          console.log('清理后的JSON字符串:', cleanJsonStr)
          aiResponse = JSON.parse(cleanJsonStr)
        } else {
          throw new Error('无法解析AI返回的JSON数据')
        }
      } catch (error) {
        console.error('解析AI响应失败:', error)
        throw new Error('AI返回的数据格式不正确')
      }



      // 处理题目内容
      const processContent = (content) => {
        if (!content) return ''

        // 移除"题干"等前缀
        content = content.replace(/^题干\s*/, '')

        // 移除答案和分析部分
        content = content.replace(/答案[：:].*$/s, '') // 移除答案部分
        content = content.replace(/分析[：:].*$/s, '') // 移除分析部分

        // 移除多余的空白字符
        content = content.replace(/\s+/g, ' ').trim()

        // 确保选项格式正确
        content = content.replace(/([A-D])\./g, '\n$1. ')

        // 移除末尾的换行符和空格
        content = content.replace(/\s+$/, '')

        return content
      }

      // 处理答案内容
      const processAnswer = (content) => {
        if (!content) return ''
        // 提取答案部分
        const answerMatch = content.match(/答案[：:]\s*([A-D])/i)
        return answerMatch ? answerMatch[1] : ''
      }

      // 提取选项
      const extractOptions = (content) => {
        if (!content) return []
        const options = []
        const optionRegex = /([A-D])[.．。]\s*([^\n]+)/g
        let match
        while ((match = optionRegex.exec(content)) !== null) {
          options.push(`${match[1]}. ${match[2].trim()}`)
        }
        return options
      }

      // 处理分析内容
      const processAnalysis = (content) => {
        if (!content) return ''
        // 提取分析部分
        const analysisMatch = content.match(/分析[：:]\s*(.*?)(?=\s*$)/s)
        return analysisMatch ? analysisMatch[1].trim() : ''
      }

      // 处理题型和科目
      const processQuestionType = (courseType, questionType) => {
        // 课程简称映射
        const courseAbbr = {
          '数据结构': 'DS',
          '计算机网络': 'CN',
          '操作系统': 'OS',
          '计算机组成原理': 'CO',
          '软件工程': 'SE'
        }

        // 题型编号映射
        const typeNumber = {
          '选择题': '01',
          '应用题': '02',
          '算法题': '03',
          '综合题': '04'
        }

        const abbr = courseAbbr[courseType] || 'OT' // 如果没有匹配的课程，使用'OT'作为默认值
        const number = typeNumber[questionType] || '99' // 如果没有匹配的题型，使用'99'作为默认值

        return {
          questionType: `${abbr}${number}`,
          subject: abbr
        }
      }

      // 构建题目数据，确保所有字段都符合数据库要求
      const { questionType: processedType, subject } = processQuestionType(
        aiGenerateForm.value.courseType,
        aiGenerateForm.value.questionType
      )

      const generatedQuestion = {
        content: processContent(aiResponse.content) || '',
        questionType: processedType,
        subject: subject,
        pointId: selectedPoint.pointId,
        courseId: selectedCourse.courseId,
        difficulty: parseInt(aiGenerateForm.value.difficulty) || 1,
        status: 1,
        answer: JSON.stringify({
          type: 'single',
          answer: processAnswer(aiResponse.content) || aiResponse.answer || '',
          options: extractOptions(aiResponse.content)
        }),
        analysis: processAnalysis(aiResponse.content) || aiResponse.analysis || '',
        reportedCount: 0
      }
      // 移除undefined和null值
      Object.keys(generatedQuestion).forEach(key => {
        if (generatedQuestion[key] === undefined || generatedQuestion[key] === null) {
          delete generatedQuestion[key]
        }
      })

      console.log('准备保存的题目数据:', generatedQuestion)

      // 保存生成的题目
      const saveResponse = await axios({
        method: 'post',
        url: 'http://localhost:8080/question/add',
        headers: {
          'Content-Type': 'application/json'
        },
        data: generatedQuestion
      })

      console.log('保存题目响应:', saveResponse.data)

      if (saveResponse.data) {
        ElMessage.success('题目生成并保存成功')
        aiGenerateDialogVisible.value = false
        loadQuestionData() // 刷新题目列表
      }
    }
  } catch (error) {
    console.error('生成题目失败，错误详情:', error)
    console.error('错误响应数据:', error.response?.data)
    console.error('错误状态码:', error.response?.status)
    ElMessage.error('生成题目失败：' + (error.response?.data?.message || error.message || '未知错误'))
  } finally {
    generating.value = false
    console.log('=== 生成题目结束 ===')
  }
}

const aiGenerateDialogVisible = ref(false);
const aiGenerateForm = ref({
  courseType: '',
  questionType: '',
  knowledgePoint: '',
  difficulty: ''
})
const generating = ref(false);

// 为智能出题模块添加独立的知识点存储
const aiKnowledgePoints = ref([]); // 新增：用于智能出题的知识点列表

// 根据选择的课程类型过滤知识点（现在直接使用 aiKnowledgePoints）
const filteredKnowledgePoints = computed(() => {
  // aiKnowledgePoints 会在 handleCourseChange 中被更新，所以这里直接返回即可
  return aiKnowledgePoints.value;
});

// 新增：处理智能出题对话框中课程类型变化的方法
const handleCourseChange = async (courseName) => {
  console.log('AI智能出题：选择课程变化，课程名称:', courseName);
  aiGenerateForm.value.knowledgePoint = ''; // 重置知识点选择
  aiKnowledgePoints.value = []; // 清空之前的知识点

  if (!courseName) {
    return;
  }

  // 根据课程名称找到对应的课程ID
  const selectedCourse = courseList.value.find(c => c.courseName === courseName);
  if (!selectedCourse) {
    console.error('未找到对应课程的ID:', courseName);
    ElMessage.error('课程信息获取失败，请重试');
    return;
  }

  try {
    console.log(`AI智能出题：正在获取知识点，课程ID: ${selectedCourse.courseId}`);
    const res = await axios.get(`http://localhost:8080/KnowledgePoint/course?courseId=${selectedCourse.courseId}`);
    if (res.data) {
      aiKnowledgePoints.value = res.data;
      console.log('AI智能出题：获取到的知识点:', aiKnowledgePoints.value);
    } else {
      console.warn('AI智能出题：获取知识点数据为空');
      aiKnowledgePoints.value = [];
    }
  } catch (error) {
    console.error('AI智能出题：获取知识点失败:', error);
    ElMessage.error('获取知识点失败，请检查网络或服务器');
    aiKnowledgePoints.value = [];
  }
};

// PDF上传相关的响应式数据
const pdfUploadDialogVisible = ref(false);
const editQuestionDialogVisible = ref(false);
const pdfUploadForm = ref({
  courseType: '',
  knowledgePoint: '',
  difficulty: '2'
});
const pdfKnowledgePoints = ref([]);
const pdfFileList = ref([]);
const extractedText = ref('');
const recognizedQuestions = ref([]);
const editingQuestion = ref({});
const pdfUploading = ref(false);
const savingQuestions = ref(false);

// 上传相关配置
const uploadAction = ref('http://localhost:8080/api/pdf/extract');
const uploadHeaders = ref({
  'Authorization': 'Bearer ' + (localStorage.getItem('token') || ''),
});

// 计算属性：为PDF上传过滤知识点
const pdfFilteredKnowledgePoints = computed(() => {
  return pdfKnowledgePoints.value;
});

// 计算属性：上传时需要传递的额外数据
const uploadData = computed(() => ({
  courseType: pdfUploadForm.value.courseType,
  knowledgePoint: pdfUploadForm.value.knowledgePoint,
  difficulty: pdfUploadForm.value.difficulty
}));

// PDF课程变化处理
const handlePdfCourseChange = async (courseName) => {
  console.log('PDF上传：选择课程变化，课程名称:', courseName);
  pdfUploadForm.value.knowledgePoint = '';
  pdfKnowledgePoints.value = [];

  if (!courseName) return;

  const selectedCourse = courseList.value.find(c => c.courseName === courseName);
  if (!selectedCourse) {
    console.error('未找到对应课程的ID:', courseName);
    ElMessage.error('课程信息获取失败，请重试');
    return;
  }

  try {
    const res = await axios.get(`http://localhost:8080/KnowledgePoint/course?courseId=${selectedCourse.courseId}`);
    if (res.data) {
      pdfKnowledgePoints.value = res.data;
      console.log('PDF上传：获取到的知识点:', pdfKnowledgePoints.value);
    }
  } catch (error) {
    console.error('PDF上传：获取知识点失败:', error);
    ElMessage.error('获取知识点失败');
  }
};

// 上传前验证
const beforePdfUpload = (file) => {
  console.log('准备上传PDF文件:', file.name);
  
  // 检查文件类型
  const isPDF = file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf');
  if (!isPDF) {
    ElMessage.error('只能上传PDF格式的文件!');
    return false;
  }

  // 检查文件大小（10MB）
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error('PDF文件大小不能超过10MB!');
    return false;
  }

  // 检查必填项
  if (!pdfUploadForm.value.courseType) {
    ElMessage.error('请先选择课程');
    return false;
  }

  if (!pdfUploadForm.value.knowledgePoint) {
    ElMessage.error('请先选择知识点');
    return false;
  }

  return true;
};

// 启动PDF上传
const startPdfUpload = async () => {
  if (pdfFileList.value.length === 0) {
    ElMessage.error('请先选择PDF文件');
    return;
  }

  // 再次验证表单
  if (!pdfUploadForm.value.courseType || !pdfUploadForm.value.knowledgePoint) {
    ElMessage.error('请完善课程和知识点信息');
    return;
  }

  pdfUploading.value = true;
  
  try {
    // 使用ref获取上传组件并触发上传
    if (pdfUploadRef.value) {
      pdfUploadRef.value.submit();
    } else {
      // 如果ref方式不行，尝试手动发送请求
      await manualPdfUpload();
    }
  } catch (error) {
    console.error('上传启动失败:', error);
    pdfUploading.value = false;
    ElMessage.error('上传启动失败，请重试');
  }
};

// 手动上传PDF的备用方法
const manualPdfUpload = async () => {
  if (pdfFileList.value.length === 0) return;
  
  const file = pdfFileList.value[0].raw || pdfFileList.value[0];
  const formData = new FormData();
  formData.append('file', file);
  formData.append('courseType', pdfUploadForm.value.courseType);
  formData.append('knowledgePoint', pdfUploadForm.value.knowledgePoint);
  formData.append('difficulty', pdfUploadForm.value.difficulty);

  try {
    const response = await axios.post(uploadAction.value, formData, {
      headers: {
        'Authorization': uploadHeaders.value.Authorization,
        'Content-Type': 'multipart/form-data'
      }
    });
    
    handlePdfUploadSuccess(response.data, file);
  } catch (error) {
    console.error('手动上传失败:', error);
    handlePdfUploadError(error, file);
  }
};

// 智能题目内容和选项分离函数 - 核心修复
const intelligentContentSeparation = (rawText) => {
  if (!rawText) return { content: '', options: {} };
  
  console.log('=== 开始分离题目内容和选项 ===');
  console.log('原始文本:', rawText);
  
  // 更精确的选项匹配模式
  const optionPatterns = [
    // A. 内容 B. 内容 (最常见格式)
    {
      pattern: /\s*([A-D])\.\s*([^A-D]{1,200}?)(?=\s*[A-D]\.|$)/g,
      splitPattern: /\s*[A-D]\.\s*/,
      description: 'A. B. C. D. 格式'
    },
    // A) 内容 B) 内容
    {
      pattern: /\s*([A-D])\)\s*([^A-D]{1,200}?)(?=\s*[A-D]\)|$)/g,
      splitPattern: /\s*[A-D]\)\s*/,
      description: 'A) B) C) D) 格式'
    },
    // A、内容 B、内容
    {
      pattern: /\s*([A-D])、\s*([^A-D]{1,200}?)(?=\s*[A-D]、|$)/g,
      splitPattern: /\s*[A-D]、\s*/,
      description: 'A、B、C、D、格式'
    }
  ];
  
  let bestSeparation = null;
  
  // 尝试每种模式
  for (let patternInfo of optionPatterns) {
    console.log(`尝试模式: ${patternInfo.description}`);
    
    // 找到第一个选项的位置
    const firstOptionMatch = rawText.match(new RegExp(`\\s*[A-D][.、)]\\s*`));
    if (!firstOptionMatch) continue;
    
    const optionStartIndex = rawText.indexOf(firstOptionMatch[0]);
    if (optionStartIndex === -1) continue;
    
    // 分离题目内容和选项部分
    const questionContent = rawText.substring(0, optionStartIndex).trim();
    const optionsText = rawText.substring(optionStartIndex).trim();
    
    console.log('题目部分:', questionContent);
    console.log('选项部分:', optionsText);
    
    // 提取选项
    const optionMatches = [...optionsText.matchAll(patternInfo.pattern)];
    console.log('选项匹配结果:', optionMatches);
    
    if (optionMatches.length >= 2) {
      const extractedOptions = {};
      
      optionMatches.forEach(match => {
        const optionKey = match[1].toUpperCase();
        const optionContent = match[2].trim();
        
        if (optionContent && optionContent.length > 0 && optionContent.length < 200) {
          extractedOptions[optionKey] = optionContent;
        }
      });
      
      const validOptionCount = Object.keys(extractedOptions).length;
      console.log(`提取到 ${validOptionCount} 个选项:`, extractedOptions);
      
      if (validOptionCount >= 2) {
        bestSeparation = {
          content: questionContent,
          options: extractedOptions,
          pattern: patternInfo.description,
          quality: validOptionCount
        };
        
        // 如果找到4个选项，优先使用
        if (validOptionCount === 4) {
          console.log('找到完整的4个选项，使用此结果');
          break;
        }
      }
    }
  }
  
  // 如果没有找到标准格式，使用更激进的方法
  if (!bestSeparation) {
    console.log('未找到标准格式，尝试激进分离');
    const aggressiveResult = aggressiveOptionExtraction(rawText);
    if (aggressiveResult && Object.keys(aggressiveResult.options).length > 0) {
      bestSeparation = aggressiveResult;
    }
  }
  
  let finalContent = rawText;
  let finalOptions = {};
  
  if (bestSeparation) {
    finalContent = cleanQuestionContent(bestSeparation.content);
    finalOptions = bestSeparation.options;
    
    // 清理选项内容
    Object.keys(finalOptions).forEach(key => {
      finalOptions[key] = cleanOptionContent(finalOptions[key]);
    });
    
    console.log(`✅ 分离成功 - 模式: ${bestSeparation.pattern}`);
  } else {
    console.log('❌ 分离失败，使用原文本');
    finalContent = cleanQuestionContent(rawText);
  }
  
  console.log('最终题目内容:', finalContent);
  console.log('最终选项:', finalOptions);
  console.log('=== 分离完成 ===\n');
  
  return {
    content: finalContent,
    options: finalOptions
  };
};

// 激进的选项提取方法（备用）
const aggressiveOptionExtraction = (text) => {
  console.log('使用激进提取方法');
  
  // 查找所有可能的选项标记
  const possibleOptions = [];
  const optionRegex = /([A-D])[.、)]\s*([^A-D\n]{1,150}?)(?=[A-D][.、)]|$)/g;
  
  let match;
  while ((match = optionRegex.exec(text)) !== null) {
    possibleOptions.push({
      key: match[1],
      content: match[2].trim(),
      index: match.index
    });
  }
  
  if (possibleOptions.length >= 2) {
    // 找到最早的选项位置
    const firstOptionIndex = Math.min(...possibleOptions.map(opt => opt.index));
    const questionContent = text.substring(0, firstOptionIndex).trim();
    
    const options = {};
    possibleOptions.forEach(opt => {
      if (opt.content && opt.content.length > 0) {
        options[opt.key] = opt.content;
      }
    });
    
    if (Object.keys(options).length >= 2) {
      console.log('激进提取成功:', { questionContent, options });
      return {
        content: questionContent,
        options: options,
        pattern: '激进提取',
        quality: Object.keys(options).length
      };
    }
  }
  
  return null;
};

// 清理题目内容的函数
const cleanQuestionContent = (content) => {
  if (!content) return '';
  
  return content
    .replace(/^[\d\s\.、）\)]+/, '') // 移除开头的题号
    .replace(/[\s\n\r]+/g, ' ')     // 规范化空白字符
    .replace(/[?？]$/, '？')         // 统一问号格式
    .trim();
};

// 清理选项内容的函数
const cleanOptionContent = (content) => {
  if (!content) return '';
  
  return content
    .replace(/[\n\r]+/g, ' ')       // 移除换行
    .replace(/\s+/g, ' ')           // 规范化空格
    .trim();
};

// 上传成功处理函数 - 重构版本
const handlePdfUploadSuccess = (response, file) => {
  console.log('PDF上传成功，响应数据:', response);
  pdfUploading.value = false;
  
  try {
    // 处理不同的响应格式
    let data = response;
    if (typeof response === 'string') {
      try {
        data = JSON.parse(response);
      } catch (e) {
        console.error('响应数据解析失败:', e);
        ElMessage.error('服务器响应格式错误');
        return;
      }
    }
    
    // 检查响应状态
    if (!data || (!data.success && data.code !== 200 && !data.extractedText && !data.questions)) {
      ElMessage.error('PDF解析失败：' + (data?.message || data?.msg || '未知错误'));
      return;
    }
    
    // 存储提取的原始文本
    extractedText.value = data.extractedText || data.text || '';
    
    // 处理识别的题目
    const rawQuestions = data.questions || data.data || [];
    console.log('原始题目数据:', rawQuestions);
    
    if (!Array.isArray(rawQuestions) || rawQuestions.length === 0) {
      if (extractedText.value) {
        ElMessage.warning('已提取文本内容，但未识别到标准格式的题目');
      } else {
        ElMessage.warning('未从PDF中提取到有效内容');
      }
      return;
    }
    
    // 处理每个题目，确保正确分离内容和选项
    recognizedQuestions.value = rawQuestions.map((q, index) => {
      console.log(`\n=== 处理第 ${index + 1} 题 ===`);
      
      // 获取原始题目文本
      const rawQuestionText = q.content || q.question || '';
      console.log('原始题目文本:', rawQuestionText);
      
      // 智能分离题目内容和选项
      const separated = intelligentContentSeparation(rawQuestionText);
      
      // 构建最终选项
      let finalOptions = separated.options;
      let finalContent = separated.content;
      
      // 如果智能分离没有找到有效选项，尝试使用后端提供的选项
      if (Object.keys(finalOptions).length === 0) {
        console.log('智能分离未找到选项，尝试使用后端数据');
        
        if (q.options && typeof q.options === 'object') {
          finalOptions = q.options;
          console.log('使用后端选项对象:', finalOptions);
        } else if (q.optionA || q.optionB || q.optionC || q.optionD) {
          finalOptions = {
            A: q.optionA || '',
            B: q.optionB || '',
            C: q.optionC || '',
            D: q.optionD || ''
          };
          console.log('使用后端分离选项:', finalOptions);
        } else {
          // 最后尝试：如果内容包含选项但分离失败，强制使用原文本作为题目
          console.warn('所有选项提取方法都失败，使用原文本');
          finalContent = rawQuestionText;
          finalOptions = { A: '', B: '', C: '', D: '' };
        }
      }
      
      // 验证最终结果
      const hasValidOptions = Object.values(finalOptions).some(opt => opt && opt.trim().length > 0);
      if (!hasValidOptions && rawQuestionText.includes('A.')) {
        console.error('检测到题目包含选项但提取失败，进行手动修复');
        // 手动修复：如果原文本明显包含选项格式但未被提取
        const manualFixed = manualOptionFix(rawQuestionText);
        if (manualFixed) {
          finalContent = manualFixed.content;
          finalOptions = manualFixed.options;
          console.log('手动修复成功:', manualFixed);
        }
      }
      
      // 构建答案JSON
      const answerJson = {
        correct: (q.correctAnswer || q.answer || 'A').toUpperCase(),
        options: finalOptions
      };
      
      // 验证正确答案
      if (!['A', 'B', 'C', 'D'].includes(answerJson.correct)) {
        console.warn(`题目 ${index + 1} 正确答案格式异常:`, answerJson.correct);
        answerJson.correct = 'A'; // 默认为A
      }
      
      const processedQuestion = {
        id: Date.now() + index, // 临时ID
        content: finalContent, // 纯题目内容
        questionType: getQuestionTypeCode(pdfUploadForm.value.courseType),
        answer: JSON.stringify(answerJson), // 答案JSON字符串
        analysis: q.analysis || q.explanation || '',
        difficulty: parseInt(q.difficulty || pdfUploadForm.value.difficulty),
        subject: getSubjectCode(pdfUploadForm.value.courseType),
        reportedCount: 0,
        status: 1,
        pointId: null,
        courseId: null
      };
      
      console.log(`✅ 题目 ${index + 1} 处理完成:`);
      console.log('- 最终题目内容:', finalContent);
      console.log('- 最终选项:', finalOptions);
      console.log('- 答案JSON:', answerJson);
      
      return processedQuestion;
    });
    
    if (recognizedQuestions.value.length > 0) {
      ElMessage.success(`成功识别并处理 ${recognizedQuestions.value.length} 道选择题`);
      console.log('最终处理的题目:', recognizedQuestions.value);
    }
    
  } catch (error) {
    console.error('处理PDF上传响应失败:', error);
    ElMessage.error('处理上传结果失败：' + error.message);
  }
};

// 学科编码映射函数
const getSubjectCode = (courseName) => {
  const subjectMap = {
    '数据结构': 'DS',
    '算法设计': 'AL',
    '计算机网络': 'CN',
    '操作系统': 'OS',
    '数据库': 'DB',
    '软件工程': 'SE',
    '计算机组成原理': 'CO'
  };
  
  return subjectMap[courseName] || 'DS';
};

// 题目类型编码映射函数
const getQuestionTypeCode = (courseName) => {
  const typeMap = {
    '数据结构': 'DS01',
    '算法设计': 'AL01',
    '计算机网络': 'CN01',
    '操作系统': 'OS01',
    '数据库': 'DB01',
    '软件工程': 'SE01',
    '计算机组成原理': 'CO01'
  };
  
  return typeMap[courseName] || 'DS01';
};

// 上传失败处理
const handlePdfUploadError = (error, file) => {
  console.error('PDF上传失败:', error);
  pdfUploading.value = false;
  
  let errorMessage = '上传失败';
  if (error.response) {
    errorMessage = error.response.data?.message || error.response.data?.msg || `服务器错误 (${error.response.status})`;
  } else if (error.message) {
    errorMessage = error.message;
  }
  
  ElMessage.error('PDF文件上传失败：' + errorMessage);
};

// 编辑识别的题目
const editRecognizedQuestion = (question) => {
  // 深拷贝题目数据，解析答案JSON用于编辑
  const questionCopy = { ...question };
  
  try {
    const answerData = JSON.parse(question.answer);
    questionCopy.correctAnswer = answerData.correct;
    questionCopy.options = answerData.options;
  } catch (error) {
    console.error('解析题目答案失败:', error);
    questionCopy.correctAnswer = 'A';
    questionCopy.options = { A: '', B: '', C: '', D: '' };
  }
  
  editingQuestion.value = questionCopy;
  editQuestionDialogVisible.value = true;
};

// 保存编辑的PDF识别题目
const savePdfEditedQuestion = () => {
  try {
    // 重新构建答案JSON
    const answerJson = {
      correct: editingQuestion.value.correctAnswer,
      options: editingQuestion.value.options
    };
    
    // 更新题目数据
    const updatedQuestion = {
      ...editingQuestion.value,
      answer: JSON.stringify(answerJson)
    };
    
    // 移除临时属性
    delete updatedQuestion.correctAnswer;
    delete updatedQuestion.options;
    
    // 更新列表中的题目
    const index = recognizedQuestions.value.findIndex(q => q.id === editingQuestion.value.id);
    if (index !== -1) {
      recognizedQuestions.value[index] = updatedQuestion;
    }
    
    editQuestionDialogVisible.value = false;
    ElMessage.success('题目编辑成功');
    
  } catch (error) {
    console.error('保存编辑题目失败:', error);
    ElMessage.error('保存失败：' + error.message);
  }
};

// 保存识别的题目到数据库
const saveRecognizedQuestions = async () => {
  const questionsToSave = recognizedQuestions.value;

  if (questionsToSave.length === 0) {
    ElMessage.warning('没有可保存的题目');
    return;
  }

  // 验证题目数据完整性
  const invalidQuestions = questionsToSave.filter(q => {
    try {
      const answerData = JSON.parse(q.answer);
      return !q.content.trim() || !answerData.correct || !answerData.options;
    } catch {
      return true;
    }
  });

  if (invalidQuestions.length > 0) {
    ElMessage.error(`发现 ${invalidQuestions.length} 道题目数据不完整，请检查后重试`);
    return;
  }

  savingQuestions.value = true;

  try {
    // 获取课程和知识点信息
    const selectedCourse = courseList.value.find(c => c.courseName === pdfUploadForm.value.courseType);
    const selectedPoint = pdfKnowledgePoints.value.find(p => p.pointName === pdfUploadForm.value.knowledgePoint);

    if (!selectedCourse || !selectedPoint) {
      throw new Error('课程或知识点信息不完整');
    }

    // 批量保存题目
    const savePromises = questionsToSave.map(question => {
      const questionData = {
        pointId: selectedPoint.pointId,
        questionType: question.questionType,
        subject: question.subject,
        difficulty: question.difficulty.toString(),
        content: question.content,
        answer: question.answer, // 已经是正确格式的JSON字符串
        analysis: question.analysis || null,
        reportedCount: 0,
        status: 1
      };

      console.log('准备保存题目:', questionData);
      return axios.post('http://localhost:8080/question/add', questionData);
    });

    await Promise.all(savePromises);
    
    ElMessage.success(`成功保存 ${questionsToSave.length} 道选择题到数据库`);
    
    // 重置状态
    resetPdfUploadState();
    
    // 刷新题目列表
    if (typeof loadQuestionData === 'function') {
      loadQuestionData();
    }
    
  } catch (error) {
    console.error('批量保存题目失败:', error);
    ElMessage.error('保存题目失败：' + (error.response?.data?.message || error.message));
  } finally {
    savingQuestions.value = false;
  }
};

// 重置PDF上传状态
const resetPdfUploadState = () => {
  pdfUploadDialogVisible.value = false;
  extractedText.value = '';
  recognizedQuestions.value = [];
  pdfFileList.value = [];
  pdfUploadForm.value = {
    courseType: '',
    knowledgePoint: '',
    difficulty: '2'
  };
};

// PDF对话框关闭处理
const handlePdfDialogClose = (done) => {
  if (pdfUploading.value) {
    ElMessage.warning('正在上传中，请稍候...');
    return;
  }
  
  if (savingQuestions.value) {
    ElMessage.warning('正在保存题目，请稍候...');
    return;
  }
  
  resetPdfUploadState();
  done();
};

// 删除识别的题目
const deleteRecognizedQuestion = (questionId) => {
  const index = recognizedQuestions.value.findIndex(q => q.id === questionId);
  if (index !== -1) {
    recognizedQuestions.value.splice(index, 1);
    ElMessage.success('题目删除成功');
  }
};

// 解析答案JSON的辅助函数
const parseAnswerJson = (answerString) => {
  try {
    return JSON.parse(answerString);
  } catch (error) {
    console.error('解析答案JSON失败:', error);
    return {
      correct: 'A',
      options: { A: '', B: '', C: '', D: '' }
    };
  }
};

// 获取题目的选项文本（用于显示）
const getQuestionOptions = (question) => {
  const answerData = parseAnswerJson(question.answer);
  return answerData.options || {};
};

// 获取题目的正确答案（用于显示）
const getCorrectAnswer = (question) => {
  const answerData = parseAnswerJson(question.answer);
  return answerData.correct || 'A';
};

// 手动修复选项提取（最后的备用方案）
const manualOptionFix = (text) => {
  console.log('尝试手动修复选项提取');
  
  // 使用更严格的分割方式
  const parts = text.split(/\s*([A-D][.、)])\s*/);
  
  if (parts.length < 5) { // 至少要有题目 + A + 内容 + B + 内容
    return null;
  }
  
  const content = parts[0].trim();
  const options = {};
  
  // 从分割结果中提取选项
  for (let i = 1; i < parts.length; i += 2) {
    const optionLabel = parts[i];
    const optionContent = parts[i + 1];
    
    if (optionLabel && optionContent) {
      const key = optionLabel.replace(/[.、)]/, '').trim().toUpperCase();
      if (['A', 'B', 'C', 'D'].includes(key)) {
        options[key] = optionContent.trim();
      }
    }
  }
  
  if (Object.keys(options).length >= 2 && content.length > 0) {
    console.log('手动修复成功:', { content, options });
    return { content, options };
  }
  
  return null;
};

// 测试选项分离功能
const testOptionSeparation = () => {
  const testCases = [
    '万维网的基本通信协议是？ A. FTP B. SMTP C. HTTP D. DNS',
    '以下哪个不是网络协议？ A) TCP B) UDP C) HTML D) IP',
    '计算机网络的拓扑结构包括： A、星型 B、环型 C、总线型 D、树型'
  ];
  
  console.log('=== 测试选项分离功能 ===');
  testCases.forEach((testCase, index) => {
    console.log(`\n测试用例 ${index + 1}: ${testCase}`);
    const result = intelligentContentSeparation(testCase);
    console.log('分离结果:', result);
  });
};

// 验证题目数据格式
const validateQuestionData = (question) => {
  const errors = [];
  
  if (!question.content || !question.content.trim()) {
    errors.push('题目内容不能为空');
  }
  
  try {
    const answerData = JSON.parse(question.answer);
    if (!answerData.correct || !['A', 'B', 'C', 'D'].includes(answerData.correct)) {
      errors.push('正确答案格式错误');
    }
    
    if (!answerData.options || typeof answerData.options !== 'object') {
      errors.push('选项格式错误');
    } else {
      const hasValidOptions = ['A', 'B', 'C', 'D'].some(key => 
        answerData.options[key] && answerData.options[key].trim()
      );
      if (!hasValidOptions) {
        errors.push('至少需要一个有效选项');
      }
    }
  } catch (e) {
    errors.push('答案JSON格式错误');
  }
  
  return errors;
};
</script>


<style scoped>
.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
}

.el-pagination {
  justify-content: center;
}

/* 原有样式保持不变 */
.main-container {
  width: 80%;
  margin: auto;
  padding: 30px;
  background-color: var(--background-color, #eef1f5);
  border-radius: 16px;
  box-shadow: 10px 10px 10px #eef1f5, -10px -10px 10px #f5f7fa;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}


.main-content {
  width: 90%;
  max-width: 1200px;
  margin: 0 auto;
  flex: 2;
  padding: 25px;
  min-height: 500px;
  border-radius: 12px;
  background-color: #ebecee;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 标题部分 */
.header {
  text-align: center;
}

.header h3 {
  margin: 0;
  font-weight: 900;
  font-size: 2rem;
  color: #212121;
}

/* 卡片通用样式 */
.material-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  transition: box-shadow 0.3s ease;
}

.material-card:hover {
  box-shadow: 0 4px 19px rgba(0, 0, 0, 0.25);
}

/* 按钮组卡片 - 去除多余内边距让按钮更紧凑 */
.top-bar-card {
  padding: 12px 30px;
}

/* 按钮组布局 */
.top-bar {
  display: flex;
  gap: 12px;
  justify-content: flex-start;
  align-items: center;
}

/* 表格卡片 padding 保持标准 */
.table-card {
  padding: 20px;
}

.custom-btn {
  transition: all 0.3s ease;
  background-color: #60879f;
  border: 1px solid #ccc;
  color: #f3f0e9 !important;
}



.custom-btn:hover {
  box-shadow: 0 4px 5px rgba(0, 0, 0, 0.25);
  background-color: #8792;
  color: #000000 !important;

}

.el-button {
  color: #333;
  outline: none;
  box-shadow: none;
  outline: none;
  box-shadow: none;
  margin-bottom: 10px;
  margin-top: 10px;
}

/* 标签栏样式 */
.el-tabs--card>.el-tabs__header {
  border-bottom: none;

}

.el-tabs--card>.el-tabs__header .el-tabs__item {
  border: none;
  border-radius: 4px;
  margin-right: 8px;
  background-color: #5e687e;
}

.el-tabs--card>.el-tabs__header .el-tabs__item.is-active {
  background-color: #385565;
  color: white;

}

/* 修改特定标签的样式 */
:deep(.el-tabs__item:nth-child(1)),
:deep(.el-tabs__item:nth-child(2)),
:deep(.el-tabs__item:nth-child(3)) {
  background-color: #60879f;
  color: #f3f0e9;
}

/* 激活状态 */
:deep(.el-tabs__item.is-active:nth-child(1)),
:deep(.el-tabs__item.is-active:nth-child(2)),
:deep(.el-tabs__item.is-active:nth-child(3)) {
  background-color: #446072;
  color: #f3f0e9;

}

:deep(.el-tabs__header) {
  border-bottom: none !important;
}

/* 移除激活标签的下划线 */
:deep(.el-tabs__active-bar) {
  display: none !important;
}

.extracted-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-wrap;
}

.upload-demo {
  width: 100%;
}
.dialog-footer {
  text-align: right;
  padding: 10px 20px;
}

.extracted-content-card {
  margin-top: 10px;
}

.extracted-content {
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-family: monospace;
}

.upload-demo {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
}
</style>